import webapp2

#
# Key Value Storage
#

from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.api import memcache

class DB_KeyValueStorage(db.Model):
  kvs_user = db.StringProperty()
  kvs_key = db.StringProperty()
  kvs_value = db.TextProperty()
  kvs_date = db.DateTimeProperty(auto_now_add=True) 

# /

class RootRedirectPage(webapp2.RequestHandler):
  def get(self):
    self.redirect('/html/keyvaluestorage.htm')

# /keyvaluestorage/api/v1/userid/

class Api_V1_UserId_Page(webapp2.RequestHandler):
  def get(self):
    cgi_callback = self.request.get("callback")
    cgi_redirect = self.request.get("redirect")
    self.response.headers['Content-Type'] = 'text/plain'
    self.response.write('/* UserId */')
    user = users.get_current_user()
    if user:
      js_responce = '{"STATUS":"login","LOGOUTURL":"%s","USERID":"%s","USERNICKNAME":"%s"}' % (
        users.create_logout_url(cgi_redirect),
        user.user_id(),
        user.nickname()
      )
    else:
      js_responce = '{"STATUS":"logout","LOGINURL":"%s"}' % (
        users.create_login_url(cgi_redirect)
      )
    #:
    self.response.write('%s (%s)' % (
      cgi_callback,
      js_responce
    ))

# /keyvaluestorage/api/v1/redirect/

class Api_V1_Redirect_Page(webapp2.RequestHandler):
  def get(self):
    cgi_redirect = self.request.get("redirect")
    self.redirect('%s' % (cgi_redirect.encode('ascii')))

# /keyvaluestorage/api/v1/itemset/

class Api_V1_ItemSet_Page(webapp2.RequestHandler):
  def get(self):
    cgi_callback = self.request.get("callback")
    cgi_key = self.request.get("key")
    cgi_value = self.request.get("value")
    self.response.headers['Content-Type'] = 'text/plain'
    self.response.write('/* ItemSet */')
    user = users.get_current_user()
    if user:
      key_name = 'kvs_u%s_k%s' % (
        user.user_id(),
        cgi_key
      )
      item = DB_KeyValueStorage(
        key_name = 'kvs_u%s_k%s' % (
          user.user_id(),
          cgi_key
        )
      )
      item.kvs_user = '%s' % (user.user_id())
      item.kvs_key = '%s' % (cgi_key)
      item.kvs_value = db.Text(cgi_value)
      item.put()
      memcache.add(key_name, item.kvs_value, 3600)
      js_responce = '{"STATUS":"login","KEY":"%s"}' % (
        cgi_key
      )
    else:
      js_responce = '{"STATUS":"logout","KEY":"%s"}' % (
        cgi_key
      )
    #:
    self.response.write('%s (%s)' % (
      cgi_callback,
      js_responce
    ))

# /keyvaluestorage/api/v1/itemget/

class Api_V1_ItemGet_Page(webapp2.RequestHandler):
  def get(self):
    cgi_callback = self.request.get("callback")
    cgi_key = self.request.get("key")
    self.response.headers['Content-Type'] = 'text/plain'
    self.response.write('/* ItemGet */')
    user = users.get_current_user()
    if user:
      key_name = 'kvs_u%s_k%s' % (
        user.user_id(),
        cgi_key
      )
      item_memcache = memcache.get(key_name)
      if item_memcache is not None: 
        item_info = 'FOUND(MC)'
        item_key = cgi_key
        item_value = item_memcache
      else:
        item = DB_KeyValueStorage.get_by_key_name(key_name)
        if item is None:
          item_info = 'NOTFOUND'
          item_key = cgi_key
          item_value = ''
        else:
          item_info = 'FOUND(DS)'
          item_key = item.kvs_key
          item_value = item.kvs_value
          memcache.add(key_name, item.kvs_value, 3600)
        #:
      #:
      js_responce = '{"STATUS":"login","INFO":"%s","KEY":"%s","VALUE":"%s"}' % (
        item_info,
        item_key,
        item_value
      )
    else:
      js_responce = '{"STATUS":"logout","KEY":"%s","VALUE":""}' % (
        cgi_key
      )
    #:
    self.response.write('%s (%s)' % (
      cgi_callback,
      js_responce
    ))

# /keyvaluestorage/api/v1/itemdel/

class Api_V1_ItemDel_Page(webapp2.RequestHandler):
  def get(self):
    cgi_callback = self.request.get("callback")
    cgi_key = self.request.get("key")
    self.response.headers['Content-Type'] = 'text/plain'
    self.response.write('/* ItemDel */')
    user = users.get_current_user()
    if user:
      key_name = 'kvs_u%s_k%s' % (
        user.user_id(),
        cgi_key
      )
      item = DB_KeyValueStorage.get_by_key_name(key_name)
      if item is None:
        item_info = 'NOTFOUND'
        item_key = cgi_key
      else:
        item_info = 'FOUND'
        item_key = item.kvs_key
        item.delete()
        memcache.delete(key_name)
      #:
      js_responce = '{"STATUS":"login","INFO":"%s","KEY":"%s"}' % (
        item_info,
        item_key
      )
    else:
      js_responce = '{"STATUS":"logout","KEY":"%s"}' % (
        cgi_key
      )
    #:
    self.response.write('%s (%s)' % (
      cgi_callback,
      js_responce
    ))

application = webapp2.WSGIApplication(
[
  ('/keyvaluestorage/api/v1/userid/', Api_V1_UserId_Page), 
  ('/keyvaluestorage/api/v1/redirect/', Api_V1_Redirect_Page), 
  ('/keyvaluestorage/api/v1/itemset/', Api_V1_ItemSet_Page), 
  ('/keyvaluestorage/api/v1/itemget/', Api_V1_ItemGet_Page), 
  ('/keyvaluestorage/api/v1/itemdel/', Api_V1_ItemDel_Page), 
  ('/', RootRedirectPage),
], 
debug=True)